<?php
namespace app\api\controller;
use think\Controller;
use think\Db;
use think\Exception;
use think\Log;
use think\Session;
use app\wap\controller\Notify as WapNotify;
use app\api\controller\Unionid;

error_reporting(E_ERROR);
ini_set('date.timezone','Asia/Shanghai');

//初始化日志

class Notify extends Controller
{
	//成功回调
    public function notify()
    {
        $jsonxm2=  file_get_contents("php://input");
        $result=$this->FromXml($jsonxm2);
        if ($result) {
            $resXml = '<xml>'."<return_code><![CDATA[SUCCESS]]></return_code>"
                ."<return_msg><![CDATA[OK]]></return_msg>" . "</xml> ";
            //记录返回数据
            log::log(json_encode($result));
            //如果成功返回了
            if ($result['return_code'] == 'SUCCESS' && $result['result_code'] == 'SUCCESS') {
                $arr['out_trade_no'] = explode('KBX',$result['out_trade_no'])[0];
                if (!$arr['out_trade_no']){
                    return false;
                }
                $order = Db::name('order') ->where(['order_no' => $arr['out_trade_no']])->field('order_status')->find();
                $member = $this->getMemberByAttach($result);
                if(empty($order)){
                    //mongo
                    $KbxOrder = new KbxOrder();
                    $kbx_order = $KbxOrder->kbx_order_by_no($arr['out_trade_no']);
                    $orderType = $kbx_order['orderType'];
                    if($orderType!="CarPool"){
                        $goods_id = $kbx_order['goods']['goodsId'];
                        $total_num_add = $kbx_order['goods']['totalnum'];
                    }else{
                        $kbx_order['id'] = $kbx_order['id']??$kbx_order['_id'];
                    }

                    //判断状态
                    $orderStatus = $kbx_order['orderStatusForUser']??$kbx_order['status']['orderStatus'];
                    $paymentStatus = $kbx_order['status']['paymentStatus'];

                    $order_status = $this->getOrderStatus($orderStatus,$paymentStatus);
                    if ($order_status>=2 && $order_status!==7){
                        return false;
                    }

                    Db::startTrans();
                    try {
                        $total_fee = $result['total_fee'] / 100;
                        //订单系统  更新order数据
                        $postUpdateArr = [
                            'id'=>$kbx_order['id'],
                            'payType' => 1,//微信支付
                            'statusPhp'=>array(
                                'orderStatus'=>2,
                            ),
                            'status'=>array(//状态（新）
                                'orderStatus'=>(new WapNotify())->statusArr[2]['orderStatus'],
                                'paymentStatus'=>(new WapNotify())->statusArr[2]['paymentStatus'],
                            ),
                        ];
                        //拼团订单 更新支付状态
                        if($orderType=="CarPool"){
                            $postUpdateArr = [
                                "carPoolOrderId"=>$kbx_order['carPoolOrder']['_id'],
                                "personalCarPoolOrderId"=>$kbx_order['_id'],
                                'payType' => 1,//微信支付
                            ];
                        }
                        $update_res = $KbxOrder->kbx_operate_order($orderType,$postUpdateArr);
                        $log[]=[
                            '订单系统API：订单支付成功-微信'=>json_encode($postUpdateArr),
                            'res'=>$update_res
                        ];
                        Log::record($log);

                        Db::name('accounts')
                            ->insert([
                                'member_id' => $member['member_id'],
                                'admin_id' => 1,
                                'order_no' => $arr['out_trade_no'],
                                'pay_order_no'=>$result['out_trade_no'],
                                'accounts_money' => $total_fee,
                                'business_way' => 1,
                                'creattime' => $result['time_end']
                            ]);
                        //如果是拼团订单需要增加拼团线路的销量
                        if(isset($kbx_order['carPoolOrder']['line']) && $line_id = $kbx_order['carPoolOrder']['line']){
                            Db::name("group_tours_line")->where(['line_id'=>$line_id])->setInc("sold_num");
                        }
                        Db::commit();
                        if($orderType=="CarPool"){
                            //延迟十秒发送订阅消息
                            //sleep(10);
                            //发送订阅消息到用户
                            $info = [
                                'thing1'=>'支付成功通知',
                                'thing2'=>'您已成功加入拼团',
                            ];
                            (new Unionid())->sendGroupTourDataToSubscribeMessage($arr['out_trade_no'],$member['member_id'],$info);
                        }
                    }catch (\PDOException $e) {
                        Db::rollback();
                        return $e->getMessage();
                    }

                    if($orderType=="CarPool"){
                        $orderDate = array(
                            'line_id'=>$kbx_order['carPoolOrder']['line'],
                            'member_id'=>$kbx_order['booker']['memberId'],
                            'order_no'=>$kbx_order['orderNo'],
                            'e_mail'=>$kbx_order['customer']['email'],
                            'phone'=>$kbx_order['customer']['username'],
                            "travel_date"=>$kbx_order['carPoolOrder']['details']['startDate'],
                        );
                    }else{
                        $orderDate = array(
                            'goods_id'=>$kbx_order['goods']['goodsId'],
                            'speedstatus'=>$kbx_order['speedStatus'],
                            'member_id'=>$kbx_order['booker']['memberId'],
                            'order_no'=>$kbx_order['orderNo'],
                            'travel_date'=>date('Y-m-d',strtotime($kbx_order['itinerary']['travelDate'])),
                            'e_mail'=>$kbx_order['contact']['email'],
                            'phone'=>$kbx_order['contact']['phone']
                        );
                    }
                    //成功下单通知
                    (new WapNotify())->gyouxiang($orderDate,$orderType,'新小V拼游订单通知【已支付】');
                    (new WapNotify())->youxiang($orderDate,$orderType);
                    // 不需要二次确认的  发送凭证修改状态
                    if(isset($kbx_order['speedStatus']) && $kbx_order['speedStatus']==0){
                        (new WapNotify())->duanxin($orderDate);
                        if($kbx_order['typeSource']=='viator'){
                            $title=$kbx_order['orderNo'];
                            $voucherUrl = "<p><b><a href='https://prelive.viatorapi.viator.com/service/merchant/voucher.jspa?code=".$dat['data']['voucherKey']."&embedResources=false'>点击下载凭证</a></b></p><br>";
                            (new WapNotify())->kbxemailcode($title,$voucherUrl,'david@kuaibangxing.com');
                        }
                    }
                    if($orderType!="CarPool"){
                        //更新销量
                        $goodssales=Db::name('goods')->where(['goods_id'=>$goods_id])->find()['goodssales'];
                        $goodssales=(int)$goodssales + $total_num_add;
                        Db::name('goods')->where(['goods_id'=>$goods_id])->update(['goodssales'=>$goodssales]);
                    }
                }else{
                    //定制系统订单
                    if ($order['order_status']>=2){
                        return false;
                    }
                    Db::startTrans();
                    try {
                        $time=time();
                        Db::name('order')
                            ->where(['order_no' => $arr['out_trade_no']])
                            ->update(['order_status' => 2,'updatetime'=>$time]);

                        $total_fee = $result['total_fee'] / 100;
                        Db::name('accounts')
                            ->insert([
                                'member_id' => $member['member_id'],
                                'admin_id' => 1,
                                'order_no' => $arr['out_trade_no'],
                                'pay_order_no'=>$result['out_trade_no'],
                                'accounts_money' => $total_fee,
                                'business_way' => 1,
                                'creattime' => $result['time_end']
                            ]);
                        Db::commit();
                    }catch (\PDOException $e) {

                        Db::rollback();
                        return $e->getMessage();
                    }
                    //成功下单通知
                    (new WapNotify())->gyouxiang($order);
                    (new WapNotify())->youxiang($order);
                    // 不需要二次确认的  发送凭证修改状态
                    if($order['speedstatus']==0){
                        (new WapNotify())->duanxin($order);
                    }
                }
                trace($resXml);
                echo $resXml;die;
            }
        }
    }
    public function FromXml($xml)
    {
        //将XML转为array
        //禁止引用外部xml实体
        libxml_disable_entity_loader(true);
        $this->values = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
        return $this->values;
    }

    public function getOrderStatus($orderStatus,$paymentStatus)
    {
        $order_status= 1;
        if($orderStatus=='pending'){
            if($paymentStatus=='pending'){
                $order_status= 1;//待付款
            }elseif($paymentStatus=='paid'){
                $order_status= 2;//已付款待使用
            }elseif($paymentStatus=='refunding'){
                $order_status= 5;//退款申请中
            }elseif($paymentStatus=='rejected'){
                $order_status= 9;//拒绝退款
            }
        }elseif($orderStatus=='toBeStarting'){//待付款
            if($paymentStatus=='paid'){
                $order_status= 2;//已付款待使用
            }elseif($paymentStatus=='refunding'){
                $order_status= 5;//退款申请中
            }elseif($paymentStatus=='rejected'){
                $order_status= 9;//拒绝退款
            }
        }elseif($orderStatus=='reviewed'){//已评价
            $order_status= 4;
        }elseif($orderStatus=='finished'){//已使用待评价
            $order_status= 3;
        }elseif($orderStatus=='canceled'){//已取消
            if($paymentStatus=='refunded'){
                $order_status= 8;//已退款
            }else{
                $order_status= 6;
            }
        }elseif($orderStatus=='expired'){//已过期
            $order_status= 7;
        }elseif($orderStatus=='unknown'){//下单失败
            $order_status= 10;
        }

        return $order_status;

    }

    //通过attch获取自定义数据
    public function getMemberByAttach($result)
    {
        $attach = $result['attach']??[];
        $attach = explode('-',$attach);
        $wxsoft = $attach[0]??'beimei';//获取小程序类型 【gtour,beimei】

        if($wxsoft=='grouptour'){
            $openid_name = "grouptour_openid";
        }else{
            $openid_name = "program_openid";
        }
        $member = Db::name('member')->where($openid_name,$result['openid'])->find();
        return $member;
    }

}

